package cn.tedu.mall.seckill.timer;

import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.RedisBloomUtils;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;

//将spuId保存到布隆过滤器中
public class SeckillBloomInitialJob implements Job {
    //查询spuId数据
    @Autowired
    private SeckillSpuMapper seckillSpuMapper;
    @Autowired
    private RedisBloomUtils redisBloomUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //首先确定保存布隆过滤器的秒杀批次的key
        //我们这里设计添加两个秒杀批次的布隆过滤器
        //避免两个批次的瞬间空档期，而且也允许用户看到下一个批次的数据
        String bloomTodayKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now());
        String bloomTomorrowKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now().plusDays(1));
        //获取spuId的集合
        Long[] spuIds = seckillSpuMapper.findAllSeckillSpuIds();
        //布隆过滤器支持String类型的数组
        String[] strSpuIds = new String[spuIds.length];
        //将spuIds集合中的值赋值到strSpuIds
        for (int i = 0; i < spuIds.length; i++) {
            strSpuIds[i]=spuIds[i]+"";
        }
        //将strSpuIds保存到布隆过滤器中
        //实际情况中，保存的秒杀批次值是不一样的
        redisBloomUtils.bfmadd(bloomTodayKey,strSpuIds);
        redisBloomUtils.bfmadd(bloomTomorrowKey,strSpuIds);
        System.out.println("将两个批次的布隆过滤器加载完成");
    }
}
